﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.ComponentModel;
using System.Windows.Data;
using Windows.UI.Core;
using System.Windows.Media.Animation;

namespace Jive.CustomControls
{
    public partial class LoadAnimationControl : UserControl, INotifyPropertyChanged
    {

        private bool _openPopup;

        public bool OpenPopup
        {
            get { return _openPopup; }
            set
            {
                if (value != _openPopup)
                {
                    _openPopup = value;
                    RaisePropertyChanged("OpenPopup");
                }
            }
        }
        
        public int ItemsRemaining
        {
            get { return (int)GetValue(ItemsRemainingProperty); }
            set { SetValue(ItemsRemainingProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ItemsRemaining.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ItemsRemainingProperty =
            DependencyProperty.Register("ItemsRemaining", typeof(int), typeof(LoadAnimationControl), new PropertyMetadata(0));


        public LoadAnimationControl()
        {
            InitializeComponent();
            
            RegisterForNotification("Visibility", this, LoadAnimation_OnVisibilityChanged);
        }
        public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)
        {
            Binding b = new Binding(propertyName) { Source = element };
            var prop = DependencyProperty.RegisterAttached("ListenName" + propertyName, typeof(object), element.GetType(), new PropertyMetadata(callback));
            element.SetBinding(prop, b);
        }
        private void LoadAnimation_OnVisibilityChanged(object e, DependencyPropertyChangedEventArgs args)
        {
            if (args.OldValue == null)
                return;
            Storyboard showAnim = Resources["RotateIcon"] as Storyboard;

            if (((Visibility)args.NewValue) == System.Windows.Visibility.Visible)
            {
                showAnim.Begin();
                OpenPopup = true;
            }
            else if (((Visibility)args.NewValue) == System.Windows.Visibility.Collapsed)
            {
                showAnim.Stop();
                OpenPopup = false;
            }

        }

        protected virtual void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}
